<template>
    <div class="search-view">
        <div class="container">
            <!-- 头部 -->
            <div class="search-header">
                <el-button @click="goBack" type="primary" plain :icon="ArrowLeft">
                    返回
                </el-button>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
                <el-input v-model="text" placeholder="请输入关键字搜索..." size="large" clearable
                    @keydown.enter="articleSearchFn" class="search-input">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                    <template #append>
                        <el-button :icon="Search" @click="articleSearchFn">搜索</el-button>
                    </template>
                </el-input>
            </div>

            <!-- 历史搜索 -->
            <div class="search-history" v-if="historys.length > 0">
                <el-card shadow="never">
                    <template #header>
                        <div class="history-header">
                            <span>
                                <el-icon>
                                    <Clock />
                                </el-icon>
                                历史搜索
                            </span>
                            <el-button text type="danger" size="small" @click="clearHistory">
                                清空
                            </el-button>
                        </div>
                    </template>
                    <div class="history-tags">
                        <el-tag v-for="(kw, index) in historys" :key="index" closable @close="removeKeyword(index)"
                            @click="chooseHistoryKeyword(kw)" class="history-tag" type="info">
                            {{ kw }}
                        </el-tag>
                    </div>
                </el-card>
            </div>

            <!-- 搜索结果 -->
            <div class="search-results">
                <div v-if="searchPerformed">
                    <div class="result-header" v-if="articles.length > 0">
                        <h3>搜索结果</h3>
                        <p>共找到 <span class="count">{{ articles.length }}</span> 篇文章</p>
                    </div>
                    <ListItem :arr="articles" />
                    <el-empty v-if="articles.length === 0" description="暂无搜索结果" />
                </div>
                <div v-else class="empty-state">
                    <el-icon class="empty-icon">
                        <Search />
                    </el-icon>
                    <p>输入关键字开始搜索</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import ListItem from '@/components/ListItem.vue'
import { useRouter } from 'vue-router'
import { articleSearch, host } from '@/api/index'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Search, Clock } from '@element-plus/icons-vue'

const router = useRouter()
const text = ref<string>("")
const articles = ref<any[]>([])
const historys = ref<string[]>([])
const searchPerformed = ref(false)

interface IItem {
    id: number
    title: string
    author: string
    content: string
    createAt: string
    src: string
    tag: string
    status?: string
    [key: string]: string | any
}

// 从本地存储加载历史记录
const historyStr = localStorage.getItem("HISTORY")
if (historyStr) {
    historys.value = JSON.parse(historyStr)
}

const goBack = () => {
    router.go(-1)
}

// 筛选已发布的文章
const filterPublishedArticles = (data: IItem[]): IItem[] => {
    return data.filter((item: IItem) => item.status === 'published')
}

// 搜索文章
const articleSearchFn = async () => {
    if (text.value.trim() == "") {
        ElMessage.warning("请输入搜索关键字")
        return
    }

    // 更新历史记录
    const keyword = text.value.trim()
    const index = historys.value.indexOf(keyword)
    if (index > -1) {
        historys.value.splice(index, 1)
    }
    historys.value.unshift(keyword)

    // 限制历史记录数量
    if (historys.value.length > 10) {
        historys.value = historys.value.slice(0, 10)
    }

    localStorage.setItem("HISTORY", JSON.stringify(historys.value))

    // 执行搜索
    articles.value = []
    searchPerformed.value = true

    await articleSearch({ keyword })
        .then((resData: any) => {
            let { result } = resData
            let arr = result.map((item: IItem) => {
                const date = new Date(item.createAt)
                item.createAt = date.toISOString()
                item.src = host + item.src
                return item
            })
            // 筛选只显示已发布的文章
            articles.value = filterPublishedArticles(arr)
        })
        .catch(() => {
            ElMessage.error("搜索失败，请稍后重试")
        })
}

// 删除单个历史记录
const removeKeyword = (index: number) => {
    historys.value.splice(index, 1)
    localStorage.setItem("HISTORY", JSON.stringify(historys.value))
}

// 清空历史记录
const clearHistory = () => {
    historys.value = []
    localStorage.removeItem("HISTORY")
    ElMessage.success("已清空历史记录")
}

// 点击历史记录关键字
const chooseHistoryKeyword = async (txt: string) => {
    text.value = txt
    await articleSearchFn()
}
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.search-view {
    min-height: calc(100vh - 300px);
    padding: 30px 0;

    .search-header {
        margin-bottom: 30px;
    }

    .search-box {
        margin-bottom: 40px;

        .search-input {
            :deep(.el-input__wrapper) {
                border-radius: 30px;
                padding: 8px 20px;
                box-shadow: @shadow-md;
                transition: all 0.3s;

                &:hover {
                    box-shadow: @shadow-lg;
                }
            }

            :deep(.el-input-group__append) {
                border-radius: 0 30px 30px 0;
                background: @primary-color;
                border-color: @primary-color;

                .el-button {
                    color: @text-white;
                    font-weight: 500;

                    &:hover {
                        background: @primary-dark;
                        border-color: @primary-dark;
                    }
                }
            }
        }
    }

    .search-history {
        margin-bottom: 40px;

        .el-card {
            border-radius: 12px;

            :deep(.el-card__header) {
                padding: 20px;
                background: @bg-primary;
            }
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 600;
            color: @text-primary;

            span {
                display: flex;
                align-items: center;
                gap: 8px;

                .el-icon {
                    font-size: 18px;
                    color: @primary-color;
                }
            }
        }

        .history-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;

            .history-tag {
                cursor: pointer;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-2px);
                    box-shadow: @shadow-sm;
                }
            }
        }
    }

    .search-results {
        .result-header {
            margin-bottom: 25px;
            padding: 20px;
            background: @bg-white;
            border-radius: 12px;
            box-shadow: @shadow-sm;

            h3 {
                font-size: 20px;
                font-weight: 600;
                color: @text-primary;
                margin: 0 0 8px 0;
            }

            p {
                color: @text-secondary;
                margin: 0;
                font-size: 14px;

                .count {
                    color: @primary-color;
                    font-weight: 600;
                    font-size: 16px;
                }
            }
        }

        .empty-state {
            text-align: center;
            padding: 100px 20px;

            .empty-icon {
                font-size: 80px;
                color: @primary-light;
                margin-bottom: 20px;
            }

            p {
                color: @text-light;
                font-size: 16px;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .search-view {
        padding: 20px 0;

        .search-box {
            margin-bottom: 30px;
        }

        .search-history {
            margin-bottom: 30px;

            .el-card {
                :deep(.el-card__header) {
                    padding: 15px;
                }
            }
        }

        .search-results {
            .result-header {
                padding: 15px;

                h3 {
                    font-size: 18px;
                }
            }

            .empty-state {
                padding: 60px 20px;

                .empty-icon {
                    font-size: 60px;
                }
            }
        }
    }
}

@media (max-width: 576px) {
    .search-view {
        .search-box {
            .search-input {
                :deep(.el-input__wrapper) {
                    padding: 6px 15px;
                }
            }
        }

        .search-results {
            .empty-state {
                padding: 40px 20px;

                .empty-icon {
                    font-size: 50px;
                }

                p {
                    font-size: 14px;
                }
            }
        }
    }
}
</style>
